﻿// Copyright (c) 2011, Adaptiv Design
// All rights reserved.
// 
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//    * Neither the name of the <ORGANIZATION> nor the names of its contributors may
// be used to endorse or promote products derived from this software without specific
// prior written permission.
// 
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

using System;
using System.Collections.Generic;
using System.Linq.Expressions;

using Alicanto.Compilation.Code;
using Alicanto.Execution;

namespace Alicanto.Compilation
{
    internal enum ScopeType
    {
        Class,
        Nested,
        Global
    }

    /// <summary>
    ///
    /// </summary>
    internal class Scope
    {
        internal Scope Outer { get; private set; }
        internal ScopeType Type { get; private set; }
        internal string Name { get; private set; }

        /// <summary>
        /// Provides references to all parameter expressions declared within this scope.
        /// </summary>
        private Dictionary<string, ParameterExpression> _declarations;

        /// <summary>
        /// Provides references to all parameter expressions (declared within this scope) that act as a argument (and thus require an argument).
        /// </summary>
        private Dictionary<string, ParameterExpression> _arguments;

        /// <summary>
        /// Provides references to all parameter expressions that are references to from within this scope. These parameter expressions are declared in a outer scope.
        /// </summary>
        private Dictionary<string, ParameterExpression> _references;

        /// <summary>
        /// When True, all declarations will be captured as arguments.
        /// </summary>
        internal bool IsCapturingArguments { get; private set; }

        private Dictionary<string, LabelTarget> _labels;

        // Execution
        internal ExecutionDomain ExecutionDomain { get; private set; }
        private ExecutionContext _executionContext;

        internal Scope(ExecutionDomain executionDomain, Scope outer)
        {
            this.Type = ScopeType.Nested;

            this.Outer = outer;
            this.ExecutionDomain = executionDomain;

            _arguments = new Dictionary<string, ParameterExpression>();
            _references = new Dictionary<string, ParameterExpression>();
            _declarations = new Dictionary<string, ParameterExpression>();

            _labels = new Dictionary<string, LabelTarget>();
            this.Delays = new List<DelayedCode>();
        }

        internal void AsExecutionContext(string name, ScopeType type)
        {
            this.Name = name;
            this.Type = type;

            _executionContext = new ExecutionContext(this, this.ExecutionDomain, this.Outer != null ? this.Outer.ExecutionContext : null);
        }

        internal void Declare(string reference, ParameterExpression parameter)
        {
            // Declare
            if (IsCapturingArguments)
                _arguments[reference] = parameter;

            _declarations[reference] = parameter;
        }

        internal void BeginArgumentSequence()
        {
            IsCapturingArguments = true;
        }

        internal void EndArgumentSequence()
        {
            IsCapturingArguments = false;
        }

        internal void RegisterLabel(string id, LabelTarget label)
        {
            if (_labels.ContainsKey(id))
                throw new Exception("A label is already registered using this id.");

            _labels[id] = label;
        }

        internal LabelTarget ResolveLabel(string id)
        {
            Scope scope = this;
            while (scope != null)
            {
                if (scope._labels.ContainsKey(id))
                    return scope._labels[id];

                scope = scope.Outer;
            }

            return null;
        }

        internal ExecutionContext ExecutionContext
        {
            get
            {
                Scope scope = this;
                while (scope != null && scope._executionContext == null)
                    scope = scope.Outer;

                if (scope._executionContext == null)
                    throw new Exception();

                return scope._executionContext;
            }
        }

        /// <summary>
        /// Returns all parameters declared in this scope.
        /// </summary>
        internal IList<ParameterExpression> Declarations
        {
            get
            {
                List<ParameterExpression> declarations = new List<ParameterExpression>();
                declarations.AddRange(_declarations.Values);

                return declarations;
            }
        }

        /// <summary>
        /// Returns all parameters that require an argument passed.
        /// </summary>
        internal IList<ParameterExpression> RequiredArguments
        {
            get
            {
                List<ParameterExpression> required = new List<ParameterExpression>();
                required.AddRange(_arguments.Values);
                return required;
            }
        }

        /// <summary>
        /// Returns all parameters that require an argument passed.
        /// </summary>
        internal IList<ParameterExpression> RequiredVariables
        {
            get
            {
                List<ParameterExpression> required = new List<ParameterExpression>();
                required.AddRange(_references.Values);
                return required;
            }
        }

        internal ParameterExpression this[string reference]
        {
            get
            {
                Scope scope = this;
                while (scope != null)
                {
                    if (scope._declarations.ContainsKey(reference))
                    {
                        if (scope != this && !_references.ContainsKey(reference))
                            // Add the reference to this scope
                            _references.Add(reference, scope._declarations[reference]);

                        return scope._declarations[reference];
                    }

                    if (scope.Type == ScopeType.Class)
                        break;

                    scope = scope.Outer;
                }

                return null;
            }
            set
            {
                Scope scope = this;
                while (scope != null)
                {
                    if (scope._declarations.ContainsKey(reference))
                    {
                        if (scope != this && !_references.ContainsKey(reference))
                            // Add the reference to this scope
                            _references.Add(reference, scope._declarations[reference]);

                        scope._declarations[reference] = value;
                        return;
                    }

                    if (scope.Type == ScopeType.Class)
                        break;

                    scope = scope.Outer;
                }

                _declarations[reference] = value;
            }
        }

        public List<Compilation.DelayedCode> Delays { get; set; }
    }
}
